package routers

import (
	"github.com/gin-gonic/gin"

	"web/pkg/app"
	"web/pkg/e"
	"web/pkg/logging"
	"web/pkg/upload"
)

// UploadImage 上传图片
func UploadImage(c *gin.Context) {
	file, image, err := c.Request.FormFile("image")
	if err != nil {
		logging.Warn(err)
		app.Fail(c, e.ERROR, err)
		return
	}

	if image == nil {
		app.Fail(c, e.INVALID_PARAMS, "图片不能为空")
		return
	}

	imageName := upload.GetImageName(image.Filename)
	fullPath := upload.GetImageFullPath()
	savePath := upload.GetImagePath()
	src := fullPath + imageName

	// 添加调试信息
	logging.Info("图片文件名: " + imageName)
	logging.Info("图片扩展名检查结果: ", upload.CheckImageExt(imageName))
	
	// 获取文件大小
	size, err := upload.GetFileSize(file)
	if err != nil {
		logging.Warn("获取文件大小失败: " + err.Error())
	} else {
		logging.Info("图片文件大小: ", size)
	}
	
	// 重置文件指针
	file.Seek(0, 0)

	if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
		logging.Warn("图片格式或大小不符合要求")
		app.Fail(c, e.ERROR_UPLOAD_CHECK_IMAGE_FORMAT, "图片格式或大小不符合要求")
		return
	}

	// 重置文件指针，确保后续保存操作能正常工作
	file.Seek(0, 0)

	err = upload.CheckImage(fullPath)
	if err != nil {
		logging.Warn(err)
		app.Fail(c, e.ERROR_UPLOAD_CHECK_IMAGE_FAIL, err)
		return
	}

	if err := c.SaveUploadedFile(image, src); err != nil {
		logging.Warn(err)
		app.Fail(c, e.ERROR_UPLOAD_SAVE_IMAGE_FAIL, err)
		return
	}

	app.Success(c, map[string]string{	
		"image_url":      upload.GetImageFullUrl(imageName),
		"image_save_url": savePath + imageName,
	})
}
